RenderPartial to String in ASP.NET MVC

October 12th, 2009 by kevin

About a year ago I released some code that allowed you to render a partial view to a string inside your controllers in ASP.NET MVC (beta, at the time). While this solution worked, it required a whole bunch of code to achieve a fairly simple goal. Well, a lot has changed in the MVC world, and rendering a partial view to string has, thankfully, become much, much easier. (Thanks to Martin where I originally got this code from!)

Below is the code I am now using to create my RenderPartialToString method:

/// Static Method to render string - put somewhere of your choosing
public static string RenderPartialToString(string controlName, object viewData)
{
     ViewDataDictionary vd = new ViewDataDictionary(viewData);
     ViewPage vp = new ViewPage { ViewData = vd };
     Control control = vp.LoadControl(controlName);

     vp.Controls.Add(control);

     StringBuilder sb = new StringBuilder();
     using (StringWriter sw = new StringWriter(sb))
     {
         using (HtmlTextWriter tw = new HtmlTextWriter(sw))
         {
             vp.RenderControl(tw);
         }
     }

     return sb.ToString();
}

As you can see, this method is much shorter and doesn’t have any sort of additional library contingencies. Pass it a path reference to your partial view and ViewData object (maybe you want that, maybe you don’t) and away you go. The following is an example of how to call the above method from your controller:

// Controller Method
public string Create()
{
     {...}
     var viewData = new SomeViewData { Note = n };

     string s = RenderPartialToString("~/Views/Clients/Notes/ClientNotesRow.ascx", viewData);

     return s;
}

That’s all there is to it!